package b2.widget.status
{
	import b2.player.PlayerInfo;
	import b2.player.PlayerInfoManager;
	import b2.player.Status;
	import b2.player.StatusEvent;
	
	import flash.display.Sprite;

	public class StatusBar extends Sprite
	{
		private var playerId:int;
		
		private var icons:Object;
		
		private var status:Status;
		
		public static const EVERY_WIDTH:int = 50;
		
		private var positionIndex:int;
		
		public function StatusBar(playerId:int)
		{
			super();
			this.playerId = playerId;
			var playerInfo:PlayerInfo = PlayerInfoManager.getInstance().players[playerId]
			icons = new Object();
			status = playerInfo.status;
			status.addEventListener(StatusEvent.STATUS_INIT,onInit);
			status.addEventListener(StatusEvent.STATUS_CHANGE,onChange);
			status.addEventListener(StatusEvent.STATUS_ADD,onAdd);
			status.addEventListener(StatusEvent.STATUS_DELETE,onDelete);

			onInit(null);
		}
		
		public function onInit(event:StatusEvent):void
		{
			for (var s:String in status.statusList)
			{
				var icon:StatusIcon = IconFactory.createIcon(status.statusList[s]);
				icons[s] = icon;
				addIcon(icon);
			}
			
		}
		
		public function onChange(event:StatusEvent):void
		{
			(icons[event.statusIndex] as StatusIcon).refresh();
		}
		
		public function onAdd(event:StatusEvent):void
		{
			var icon:StatusIcon = IconFactory.createIcon(status.statusList[event.statusIndex]);
			icons[event.statusIndex] = icon;
			addIcon(icon);
		}
		
		private function addIcon(icon:StatusIcon):void
		{
			icon.index = positionIndex;
			icon.x = icon.index * EVERY_WIDTH;
			icon.y = 0;
			this.addChild(icon);
			icon.refresh();
			positionIndex ++;
		}
		
		private function onDelete(event:StatusEvent):void
		{
			var icon:StatusIcon = status.statusList[event.statusIndex];
			for (var s:String in icons)
			{
				var iconToMove:StatusIcon = icons[s];
				if (iconToMove.index > icon.index)
				{
					iconToMove.index--;
					iconToMove.refresh();
				}
			}
			positionIndex--;
			this.removeChild(icon);
			delete icons[event.statusIndex];
		}
		
	}
}